
var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
//构建一个连接信息
var DB_CONN_STR = "mongodb://localhost:27017/mui";
var async = require('async');

router.all('*', function(req, res, next) {  
    res.header("Access-Control-Allow-Origin", "*");  
    res.header("Access-Control-Allow-Headers", "X-Requested-With");  
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
    res.header("X-Powered-By",' 3.2.1')  
    res.header("Content-Type", "application/json;charset=utf-8");  
    next();
}); 

/* GET home page. */



router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});


//注册请求的路由
router.get('/reg', function(req, res) {
	var uname = req.query.username;
	console.log(uname);
	var upwd = req.query.password;
   // MongoClient.connect(DB_CONN_STR, function(err, db) {
   //      if (err) {
   //          console.log(err);
   //      } else {
   //          var coll = db.collection('users');

   //          coll.insert([{username:uname,password:upwd}], function(err, data) {
   //          	if (err) {
   //          		console.log(err);
   //          	} else {
   //          		res.send('成功');
   //          	}
   //          })
   //      }
   //  })
   	MongoClient.connect(DB_CONN_STR,function(err,db){
         if(err){
         	console.log(err);
         }else{
         	//得到一个集合
         	var coll = db.collection('users');
         	async.waterfall([
         		//第一个异步，判断是否有相同的用户名
         		function(cb){
                   var data = {"username":uname};
                   var num = coll.find(data).count(function(err,num){
                        if(err){
                        	consloe.log(err);
                        }else{
                        	if(num>0){
                        		cb('用户名存在');
                        	}else{
                        		cb(null);
                        	}
                        }
                   });

         		},
         		//插入数据
         		function(cb){
         			var data= {
         				"username":uname,
         				"password":upwd,
         				"images":''
         				
         			}
         			coll.insertOne(data,function(err,data){
         				if(err){
         					console.log(err);
         				}else{
         					cb(null,data);
         				}
         			})
         		}         		
         		],function(err,result){
         		if(err){
         			// res.send(err);
         			res.send({err:err});         			
         		}else{
         			res.send({msg:'注册成功'});
         			        			
         		}
         	})
         }
	})
});




//登录请求的路由
router.get('/login',function(req,res){
	var username = req.query.username;
	var password = req.query.password;
	//建立数据库连接
	MongoClient.connect(DB_CONN_STR,function(err,db){
       if(err){
       	console.log(err);
       }else{
       	var coll = db.collection('users');
       	var data = { 
       		"username":username,
       		"password":password
       	}
       	coll.find(data).toArray(function(err,result){
       		if(err){        
       			console.log(err);
       		}else{
       		 if(result.length>0) {
                console.log(result);
	            // var msg = '登录成功';
	            var loginname = result[0].username;
	            // localStorage.setItem('loginname',loginname);
	            // res.cookie('loginname',loginname,{maxAge:60*60*1000});
	            // console.log(loginname);
	            res.send({user:loginname});
           
             } else {
              var msg = '用户名或密码错误';
              // res.send({msg:err});
               res.send({msg:msg});
             }
            
       		}
       	})
       }
	})
})
//存储照片
router.get('/clip',function(req,res){
	   var  images = req.body.imgsrc;
	   var  username = req.body.username;
	   MongoClient.connect(DB_CONN_STR,function(err,db){
       if(err){
       	console.log(err);
       }else{
       	var coll = db.collection('users');
       	coll.update({username:username},{$set:{images:images}},function(err,data){
       		if(err){        
       			console.log(err);
       			res.send('失败');
       		}else{
       			res.send('成功');
                console.log(data);
       		}
       	})
       }
	})

     
})
module.exports = router;
